package com.bigfreakindeals.Activities;


import java.util.ArrayList;

import com.bigfreakindeals.R;
import com.bigfreakindeals.Activities.DiscussActivity.DiscussAdapter.ViewHolder;
import com.bigfreakindeals.Adapters.CouponsAdapter;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.ImageEngine;
import com.bigfreakindeals.Controller.ImageListener;
import com.bigfreakindeals.Models.ActiveDeal;
import com.bigfreakindeals.Models.BarCouponItem;
import com.bigfreakindeals.Models.BeansSays;
import com.bigfreakindeals.Models.Branch;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Models.Coupons;
import com.bigfreakindeals.Models.DiscussionComment;
import com.bigfreakindeals.Models.ObjectImage;
import com.bigfreakindeals.Models.UniversityDeals;
import com.bigfreakindeals.Protocols.SoapHandlers.FAQHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.MarkCouponsHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.MyCouponsHandler;
import com.bigfreakindeals.Widgets.AlertManager;
import com.google.android.maps.Overlay.Snappable;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation.ActivityResult;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
//import android.content.ClipData.Item;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;



public class MyCouponActivity extends Activity  implements OnClickListener, ImageListener, OnItemClickListener{
	   // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

	private boolean onFetch = false;
	
	private boolean onFetchBarCode = false;
	
	Button headerButtonLeft;
	Button headerButtonRight;
	
	
	
	CouponsAdapter adapter;
	ListView listview;
	String sessionid = null;
	Button refresh;
	Button map;
	LinearLayout headertopBG;
	LinearLayout headerbottomBG;
	LinearLayout branches;
	TextView phone;
	TextView website;
	
	Integer lock = new Integer(1);
	boolean isDetailed =false;
	Coupons selectedCoupon = null;
	LayoutInflater inflater;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.nomycoupons);
		
		((ProgressBar) findViewById(R.id.progress)).setVisibility(View.VISIBLE);
		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		this.registerReceiver(myCouponsBroadcastReceiver, new IntentFilter(Constant.EVENTS_MYCOUPONSLIST));
		this.registerReceiver(myCouponsBroadcastReceiver, new IntentFilter(Constant.EVENTS_NOCOUPONSLIST));
		this.registerReceiver(myCouponsBroadcastReceiver, new IntentFilter(Constant.EVENTS_MARKUSED_COUPON_ERROR));
		this.registerReceiver(myCouponsBroadcastReceiver, new IntentFilter(Constant.EVENTS_MARKUSED_COUPON_SUCCESS));
		onFetchBarCode = false;
	}
	


	public void SignIn(){
		Intent intent = new Intent(this, LoginActivity.class);
		intent.putExtra(Constant.TAG_LOGINFROM, Constant.TAG_LOGINFROM_MYCOUPONS);
		startActivity(intent);
		
 	}
	private void getMyCoupons(){
		
		// start pulling the latest deals
		final ArrayList<String> params = new ArrayList<String>();
		if (sessionid==null)
			sessionid = ApplicationEx.getInstance().myProfile.getSessionID();
		
		params.add(sessionid);
		
			new Thread() {
				public void run() {
					try {
						sleep(5);
					} catch (Exception e) {
					}
					onFetch = true;
					new MyCouponsHandler(Tools.getURL(Constant.GET_MYCOUPONS,params));	
				}

			}.start();
			
		
	}
private void markCoupons(String couponid){
		
		// start pulling the latest deals
		final ArrayList<String> params = new ArrayList<String>();
		if (sessionid==null)
			sessionid = ApplicationEx.getInstance().myProfile.getSessionID();
		
		params.add(sessionid);
		params.add(couponid);
		
			new Thread() {
				public void run() {
					try {
						sleep(5);
					} catch (Exception e) {
					}
					new MarkCouponsHandler(Tools.getURL(Constant.GET_MARKUSED,params));	
				}

			}.start();
			
		
	}
public void displayErrorMessage(String errorMessage){
	AlertManager.alertOK(this,errorMessage, "OK");
}
public void setConfirmAlert(final String couponID){
	   
  	AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
		builder.setMessage("You are about to redeem this BigFreakinDeals coupon. " +
				"This BigFreakinDeals coupon can only be redeemed once!" +
				" Are you sure?")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel(); 
		        	   dialog.dismiss();
		        	   markCoupons(couponID);
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
		
	}

	public void getImage(final String feed, final String couponId, final String imageType/*identify if small medium or large*/) {
		
		final ImageListener listener = this;
		// In all cases, start a background thread.
		Thread thread = new Thread() {
			public void run() {
				try {
					Thread.sleep(1);
					ImageEngine.getInstance().getImage(new ObjectImage(feed, listener, couponId, imageType));
				} catch (InterruptedException ex) {
				}
			}

		};
		thread.start();
	}
	@Override
	 public void onConfigurationChanged(Configuration newConfig) {
	 super.onConfigurationChanged(newConfig);
	 }
	public void unregister() {
		this.unregisterReceiver(myCouponsBroadcastReceiver);
	}
	
	public BroadcastReceiver myCouponsBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			try{
				((ProgressBar) findViewById(R.id.progress)).setVisibility(View.INVISIBLE);
			}catch (Exception e) {
				// TODO: handle exception
			}
			
			
			if (intent.getAction().equals(Constant.EVENTS_MYCOUPONSLIST)) {
				fetchImages(false);
				updateImageCoupons();
				updateUniversityTheme("My Coupons");
			} else if (intent.getAction().equals(Constant.EVENTS_NOCOUPONSLIST)) {
				getActivityView();
			}else if (intent.getAction().equals(Constant.EVENTS_MARKUSED_COUPON_ERROR)) {
				String errormessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
			   	displayErrorMessage(errormessage);
			}else if (intent.getAction().equals(Constant.EVENTS_MARKUSED_COUPON_SUCCESS)) {
				displayErrorMessage("BigFreakinDeals coupon redeeemed!");
				getActivityView();
				
				try{
					((ProgressBar) findViewById(R.id.progress)).setVisibility(View.VISIBLE);
				}catch (Exception e) {
					// TODO: handle exception
				}
				
			}
		}
	};
	
	private void fetchImages(boolean isBarcode){
		
		 if (isBarcode){
			 	if (selectedCoupon.barCoupons!=null && selectedCoupon.barCoupons.size()>0){ //fetch all barcodes too
			 		ArrayList<BarCouponItem> items = selectedCoupon.barCoupons;
			 		for (int i = 0; i<  items.size();i++){
			 			BarCouponItem item = items.get(i);
			 				System.out.println("get that image");
			 			if (item.barcodeImg==null){
			 				getImage(item.barCodeString, selectedCoupon.dealID,"barcode_"+item.couponID) ;
			 				return;
			 			}
			 		}
			 
			 		return;
			 	}
			 	return;
			
		 } 
		 
		 if (ApplicationEx.getInstance().myProfile.myCoupons!=null){
				 
		   for (int i = 0; i<  ApplicationEx.getInstance().myProfile.myCoupons.length;i++){
			   Coupons	coupons = ApplicationEx.getInstance().myProfile.myCoupons[i];
			   getImage(coupons.thumbnailmedium_URL, coupons.dealID+"_"+coupons.thumbnailmedium_URL, coupons.thumbnailmedium_URL/*identify if small medium or large*/) ;
				    	
		   }
		 }	
			
	}
	public synchronized void getRedeemView(){
		if (selectedCoupon!=null && selectedCoupon.coupons_remaining!=null) {
			System.out.println("redeem view 1");
			setContentView(R.layout.redeem);
			
			headerButtonLeft = (Button)findViewById(R.id.header_iconright);
			headerButtonLeft.setOnClickListener(this);
			headerButtonLeft.setSelected(true);
			headerButtonLeft.setBackgroundResource(R.drawable.btn_support);
			
			headerButtonRight = (Button)findViewById(R.id.header_iconleft);
			headerButtonRight.setVisibility(View.INVISIBLE);
			headertopBG = (LinearLayout) findViewById(R.id.headerbg_top);
			headerbottomBG = (LinearLayout) findViewById(R.id.headerbg_bottom);
			if (headerbottomBG != null)
				headerbottomBG.setBackgroundColor(0xff090909);
			
			if (headertopBG != null)
					headertopBG.setBackgroundColor(0xff404040);
			
			TextView headerTitle = (TextView) findViewById(R.id.header_title);
			headerTitle.setText("Redeem");
			headerTitle.setTextColor(0xffffffff);
			synchronized (selectedCoupon) {
				System.out.println("redeem view 1");
				populateBarCoupons(selectedCoupon);	
			}
		}
		
	}
	public void populateBarCoupons(Coupons coupon){
		LinearLayout list = (LinearLayout)findViewById(R.id.redeemlist);
		LinearLayout couponitem; 
		ArrayList<BarCouponItem> couponlist = coupon.barCoupons;
		list.removeAllViews();
		System.out.println("redeem view 2");
		for (int index = 0; index< couponlist.size(); index++){
			System.out.println("redeem view 3");
			BarCouponItem item = couponlist.get(index);
			couponitem = (LinearLayout)inflater.inflate(R.layout.coupon_barcode, null);
			((TextView)couponitem.findViewById(R.id.couponid)).setText("Coupon #"+item.couponCode);
			((TextView)couponitem.findViewById(R.id.title)).setText(coupon.dealname);
			((TextView)couponitem.findViewById(R.id.couponnumber)).setText(item.couponID);
			((Button)couponitem.findViewById(R.id.btn_markcoupon)).setOnClickListener(this);
			((Button)couponitem.findViewById(R.id.btn_markcoupon)).setTag(item.couponID);
			
			if (item.barcodeImg==null)
			{System.out.println("redeem view 4"+onFetchBarCode);
			
				if (!onFetchBarCode){
					onFetchBarCode = true;
					fetchImages(true);
				}
				((ImageView)couponitem.findViewById(R.id.couponbarcode)).setVisibility(View.GONE);
				((ProgressBar)couponitem.findViewById(R.id.barcodeprogress)).setVisibility(View.VISIBLE);
			}else {
				((ProgressBar)couponitem.findViewById(R.id.barcodeprogress)).setVisibility(View.GONE);
				((ImageView)couponitem.findViewById(R.id.couponbarcode)).setImageBitmap(item.barcodeImg);
				((ImageView)couponitem.findViewById(R.id.couponbarcode)).setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
				
			}
			list.addView(couponitem,new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
		
		}
		
		
	}
		
	public void getDetailedView(){
		if (selectedCoupon!=null){
		setContentView(R.layout.mycouponsdetailed);
		
		branches = ((LinearLayout)findViewById(R.id.branches));
	 	phone = ((TextView)findViewById(R.id.phone));
		website = ((TextView)findViewById(R.id.website));
		
		
		((TextView) findViewById(R.id.coupon_title)).setText(selectedCoupon.company.getCompanyname());
		
		((Button)findViewById(R.id.btn_usethiscoupon)).setOnClickListener(this);
		
		
		((Button)findViewById(R.id.header_iconleft)).setVisibility(View.INVISIBLE);
		((TextView) findViewById(R.id.coupon_testdeal)).setText(selectedCoupon.dealname);
		
		
		
		if (selectedCoupon.company.hasBranchOffice()){
			branches.setVisibility(View.GONE);
			branches.removeAllViews();
			LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View customView;
			for (int i = 0; i < selectedCoupon.company.getBranchCount(); i++) {
				Branch branch = (Branch) selectedCoupon.company.getBranchOffice().get(i);
				customView = linflater.inflate(R.layout.branchitem, null);
				((TextView) customView.findViewById(R.id.branchaddress1)).setText(branch.getCompanyAddress1());
				((TextView) customView.findViewById(R.id.branchcitystatezip)).setText(branch.cityStateZip());
				customView.setTag(i);
				customView.setId(i);
				customView.setOnClickListener(this);
				branches.addView(customView);

			}
			if (branches.getVisibility() == View.VISIBLE){
				((TextView) findViewById(R.id.location)).setText(selectedCoupon.company.getBranchCount()+" more location  ");
				((TextView) findViewById(R.id.location)).setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.arrow_up_gray),null);
				
			}else {
				((TextView) findViewById(R.id.location)).setText(selectedCoupon.company.getBranchCount()+" more location  ");
				((TextView) findViewById(R.id.location)).setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.arrow_down_gray),null);
				
			}
			((TextView) findViewById(R.id.location)).setOnClickListener(this);
		}
		
		if (selectedCoupon.company.getPhoneNumber() !=null){
			phone.setText(selectedCoupon.company.getPhoneNumber());
			phone.setOnClickListener(this);
		}else 
			phone.setVisibility(View.INVISIBLE);
		
	
		if (selectedCoupon.company.getWebSite() !=null){
			website.setText(selectedCoupon.company.getWebSite());
			website.setOnClickListener(this);
		}else 
			website.setVisibility(View.INVISIBLE);
	
		((TextView) findViewById(R.id.seetherules)).setOnClickListener(this);
	
		
		((ImageView)findViewById(R.id.thumbnail)).setImageBitmap(selectedCoupon.thumbnailmedium);
		
		map = ((Button)findViewById(R.id.header_iconright));
		
		map.setTag(R.id.company_latitude,selectedCoupon.company.getLatitude());
		map.setTag(R.id.company_longitude,selectedCoupon.company.getLongitude());
		map.setTag(R.id.company_name,selectedCoupon.company.getCompanyname());
		map.setTag(R.id.company_dealname,selectedCoupon.dealname);
		map.setOnClickListener(this);
		map.setBackgroundResource(R.drawable.btn_map);
		
		((TextView) findViewById(R.id.txt_available_num)).setText(selectedCoupon.coupons_remaining  +" of "+selectedCoupon.total_count);
		((TextView) findViewById(R.id.txt_date)).setText(selectedCoupon.coupons_expirydate);
		((TextView) findViewById(R.id.instructionsstring)).setText(selectedCoupon.instructions);
		
		((TextView) findViewById(R.id.address1)).setText(selectedCoupon.company.getCompanyAddress1());
		((TextView) findViewById(R.id.address2)).setText(selectedCoupon.company.getCompanyAddress2());
		
		((TextView) findViewById(R.id.citystatezip)).setText(selectedCoupon.company.cityStateZip());
		
		((TextView) findViewById(R.id.coupon_item)).setText(selectedCoupon.description);
		
		updateUniversityTheme(selectedCoupon.company.getCompanyname());
		}
		
	}
	private void loadCoupons(){
			setContentView(R.layout.mycouponslist);
			
			listview = ((ListView) findViewById(R.id.mycoupons));
			listview.setVisibility(View.VISIBLE);
			
			((LinearLayout) findViewById(R.id.separator_main)).setVisibility(View.GONE);
			
			refresh = ((Button)findViewById(R.id.header_iconright));
			refresh.setOnClickListener(this);
			refresh.setBackgroundResource(R.drawable.refresh);
			
			try{
			
				((Button)findViewById(R.id.header_iconleft)).setVisibility(View.INVISIBLE);
				((ProgressBar) findViewById(R.id.progress)).setVisibility(View.INVISIBLE);
				onFetch = false;
			
			}catch (Exception e) {
			}
			synchronized (ApplicationEx.getInstance().myProfile.myCoupons) {
					adapter = new CouponsAdapter(this.getParent(), 
					R.layout.mycouponsitem, 
					ApplicationEx.getInstance().myProfile.myCoupons);
					
					listview.setAdapter(adapter);
					adapter.setItems(ApplicationEx.getInstance().myProfile.myCoupons);
					adapter.notifyDataSetChanged();
					adapter.notifyDataSetInvalidated();
					listview.setAdapter(adapter);
					
					listview.setOnItemClickListener(this);
			}
			updateUniversityTheme("My Coupons");
				
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {
		isDetailed = true;
		
		selectedCoupon = ApplicationEx.getInstance().myProfile.myCoupons[pos];
	
		getDetailedView();
	
	}
	public void getActivityView()	{  
		

		if (!ApplicationEx.getInstance().myProfile.isLogin()){
			
			setContentView(R.layout.mycoupons_signout);
			((TextView) findViewById(R.id.header_title)).setText("My Coupons");
			((TextView) findViewById(R.id.header_title)).setTextColor(0xffffffff);
			((LinearLayout)findViewById(R.id.container)).setBackgroundDrawable(Tools.getDrawableButtonGeneric(new int[]{0xffffffff, 0xffd0d0d0}, 10));
			((Button) findViewById(R.id.button_signup)).setOnClickListener(this);
			
			if (ApplicationEx.getInstance().myProfile!=null && ApplicationEx.getInstance().myProfile.getlastSelectedSchool()!=null)
				((RelativeLayout)findViewById(R.id.main)).setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().color_school_bg + (-16777216));
			
		
		}else {
			System.out.println("getActivityView:"+onFetch);
			
			if (!onFetch){
				
				setContentView(R.layout.nomycoupons);
				
				sessionid = ApplicationEx.getInstance().myProfile.getSessionID();
				
				((ProgressBar) findViewById(R.id.progress)).setVisibility(View.VISIBLE);
				((RelativeLayout) findViewById(R.id.nocoupons)).setVisibility(View.INVISIBLE);
				((Button)findViewById(R.id.header_iconleft)).setVisibility(View.INVISIBLE);
				((RelativeLayout)findViewById(R.id.main)).setBackgroundColor(0xffffffff);
				
				refresh = ((Button)findViewById(R.id.header_iconright));
				refresh.setOnClickListener(this);
				refresh.setBackgroundResource(R.drawable.refresh);
				if (ApplicationEx.getInstance().myProfile.myCoupons!=null && ApplicationEx.getInstance().myProfile.myCoupons.length>0 ){
					System.out.println("loadCoupons:"+onFetch);
					
					loadCoupons();
				}else 
				getMyCoupons();
				
			}else {
				System.out.println("getActivityView:"+onFetch);
				
				if (ApplicationEx.getInstance().myProfile.myCoupons!=null && ApplicationEx.getInstance().myProfile.myCoupons.length>0 ){
					System.out.println("loadCoupons:"+onFetch);
					
					loadCoupons();
				}else{
					setContentView(R.layout.nomycoupons);
					((ProgressBar) findViewById(R.id.progress)).setVisibility(View.INVISIBLE);
					onFetch = false;
					((RelativeLayout) findViewById(R.id.nocoupons)).setVisibility(View.VISIBLE);
					((TextView) findViewById(R.id.header_title)).setText("My Coupons");
					((TextView) findViewById(R.id.header_title)).setTextColor(0xffffff);
					((RelativeLayout)findViewById(R.id.main)).setBackgroundColor(0xffffffff);
					((Button)findViewById(R.id.header_iconleft)).setVisibility(View.GONE);
					
					refresh = ((Button)findViewById(R.id.header_iconright));
					refresh.setOnClickListener(this);
					refresh.setBackgroundResource(R.drawable.refresh);
				
				}
				
				
			}
			
		}
		
		
		updateUniversityTheme("My Coupons");
		
		
	}
	
	public void updateUniversityTheme(String title) {
		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolTitle() != null) {
			TextView headerTitle = (TextView) findViewById(R.id.header_title);
			headerTitle.setText(title);
			headerTitle.setTextColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().color_school_font+ (-16777216));
			
		}

		headertopBG = (LinearLayout) findViewById(R.id.headerbg_top);
		headerbottomBG = (LinearLayout) findViewById(R.id.headerbg_bottom);
		
		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarBottomColor() > -1
				&& ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarTopColor() > -1) {
			if (headerbottomBG != null)
				headerbottomBG.setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarBottomColor()
						+ (-16777216));

			if (headertopBG != null)
				headertopBG
						.setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarTopColor() + (-16777216));
		}
		
	}
	
	@Override
	public void onResume(){
		
		super.onResume();
		ApplicationEx.getInstance().currentTab = 1;
		getActivityView();
		
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		if ( keyCode == KeyEvent.KEYCODE_BACK) {
			if (isDetailed ){
				isDetailed = false;
				onFetch = true;
				updateImageCoupons();
				return true;
			}else {
				((TabActivity)getParent()).getTabHost().setCurrentTab(0);
				return true;
			}
	    	
		}
    	return super.onKeyDown(keyCode,event);
    	   
	}
	public void refresh(){
		
		((ProgressBar) findViewById(R.id.progress)).setVisibility(View.VISIBLE);
		
		getMyCoupons();
		
		
	}
	public void getMap(String lat, String longi,String companyname,String dealname){
		
	
			
		//call map intent
		Intent intent = new Intent(this, BigfreakinDealsMapsActivity.class);
		intent.putExtra(Constant.TAG_COMPANY_LATITUDE, lat);
		intent.putExtra(Constant.TAG_COMPANY_LONGITUDE, longi);
		intent.putExtra(Constant.TAG_COMPANY_NAME, companyname);
		intent.putExtra(Constant.TAG_COMPANY_DEALTITLE, dealname);
		
		startActivity(intent);
		
	}
	private void call(String url){
		// get the number
		String number = url.replaceAll(" ", "");
		try {
			Intent intent = new Intent(Intent.ACTION_CALL);
			intent.setData(Uri.parse("tel:" + number));
			startActivity(intent);
		} catch (Exception e) {
		
		}
	}
private void gotowebsite(String url){
	// get the url
	try {
			Uri uriUrl = Uri.parse(url);
			Intent i = new Intent(Intent.ACTION_VIEW, uriUrl);
			startActivity(i);

	} catch (Exception e) {
		e.printStackTrace();
	}
	}
	
	@Override
	public void onClick(View v) {
		 if (v == refresh){
			 	if (!onFetch){
					refresh();
				}else 
					onFetch = false;
		}else if (v == map){
				
			String lat = v.getTag(R.id.company_latitude).toString();
			String longi = v.getTag(R.id.company_longitude).toString();

			String dealname = v.getTag(R.id.company_dealname).toString();

			String companyname = v.getTag(R.id.company_name).toString();
			 getMap(lat,longi,companyname,dealname);
		}
		else if (v.getId() ==R.id.btn_markcoupon){ //support
			String couponid = (v.getTag().toString());
			setConfirmAlert(couponid);
		}else if (v.getId() ==R.id.header_iconright){ //support
			
			Intent intent = new Intent(this, BrowserActivity.class);
			intent.putExtra(Constant.TAG_BROWSERTYPE, Constant.type_SUPPORT);
			startActivity(intent);
			
		}else if (v.getId() == R.id.location){
			hideDisplayBranches();
		}else if (v.getId() == R.id.phone){
			if(phone!=null && phone.getText() !=null)
				call(phone.getText().toString());
		}else if (v.getId() == R.id.website){
			if(website!=null && website.getText() !=null)
			gotowebsite(website.getText().toString());		
		}else if (v.getId() == R.id.seetherules){
			Intent intent = new Intent(this, BrowserActivity.class);
			intent.putExtra(Constant.TAG_BROWSERTYPE, Constant.type_DEALFAQ);
			startActivity(intent);
		}else if (v.getId() == R.id.btn_usethiscoupon){
			System.out.println("use this coupons");
			getRedeemView();
		}else
			SignIn();
	}
	
	 // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
        	  
            loadCoupons();
        }
    };
    
    // Create runnable for posting
    final Runnable mUpdateBarCode = new Runnable() {
        public void run() {
        	getRedeemView();
        }
    };
    private void hideDisplayBranches(){
    	
    	if (branches.getVisibility() != View.VISIBLE){
    		branches.setVisibility(View.VISIBLE);
    		//add branches
    	}else 
    		branches.setVisibility(View.GONE);
    
    	String temp = ((TextView) findViewById(R.id.location)).getText().toString();
    	if (branches.getVisibility() == View.VISIBLE){
    		((TextView) findViewById(R.id.location)).setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.arrow_up_gray),null);
			
		}else {
			((TextView) findViewById(R.id.location)).setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.arrow_down_gray),null);
			
		}
    	
    }
    
   
    protected synchronized void updateBarCode() {
    	// Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
            	mHandler.post(mUpdateBarCode);
            }
        };
        t.start();
    }
    protected synchronized void updateImageCoupons() {
    	// Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
            	mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }
private void updateImageCouponBarCode(Bitmap bm, String dealId,String couponID){
	
	if (selectedCoupon.dealID.equals(dealId) && selectedCoupon.barCoupons!=null)	{
		for (int i = 0; i<selectedCoupon.barCoupons.size(); i++){
			BarCouponItem item = selectedCoupon.barCoupons.get(i);
			
			if (item.couponID.endsWith(couponID)){
				item.barcodeImg = bm;
				selectedCoupon.barCoupons.set(i,item);
				i = selectedCoupon.barCoupons.size()+1;//end for loop
				
				int index = ApplicationEx.getInstance().myProfile.findCouponIndex(selectedCoupon);
				
				if (index != -1)
					ApplicationEx.getInstance().myProfile.myCoupons[index] = selectedCoupon;
				
				updateBarCode();
				
				fetchImages(true);
				
				
			}
			}
				
	}
	
}
	@Override
	public void imageResponse(Bitmap bitmap, String dealId/*or couponId*/, String type) {
		// TODO Auto-generated method stub
		
		if (bitmap != null && dealId != null && type != null) {
			//check if img id exist in the list of coupons
			int bitmaptype = 0;/*0=small;1=medium;2=large; 3=barcode*/
			if (type.contains("small_thumb")){
				bitmaptype = 0;
				ApplicationEx.getInstance().addCouponThumnail(bitmap, dealId.substring(0,dealId.indexOf("_")), bitmaptype);
				
			}else if (type.contains("normal_thumb")){
				bitmaptype = 1;//medium
				if (ApplicationEx.getInstance().addCouponThumnail(bitmap, dealId.substring(0,dealId.indexOf("_")), bitmaptype)){
					if (listview!=null && (listview.getVisibility() == View.VISIBLE)){
						updateImageCoupons();
					}
				}
				
			}else if (type.contains("medium_thumb")){
				bitmaptype = 2;//large
				ApplicationEx.getInstance().addCouponThumnail(bitmap, dealId.substring(0,dealId.indexOf("_")), bitmaptype);
			} else if (type.contains("barcode")){
				bitmaptype = 3;//barcode
				onFetchBarCode = false;
				updateImageCouponBarCode(Tools.getResizedBitmap(bitmap, bitmap.getHeight(),ApplicationEx.getInstance().screenWidth-40),dealId,type.substring(8));
				
				
			} 
		
		}
	}

	
}
